﻿using AutoMapper;
using MediatR;
using Sale.Api.Application.Command.ClientPrice;
using Sale.Domain;
using Sale.ErrorCode;
using Sale.Infrastructure.Implement;
using Sale.Infrastructure.Interface;

namespace Sale.Api.Application.Handler.ClientPrice
{
    public class AddClientPriceHandler : IRequestHandler<AddClientPriceCommand, ApiResult<int>>
    {
        private readonly ILogger<AddClientPriceHandler> logger;
        private readonly IMapper mapper;
        private readonly DatabaseContext db;

        public AddClientPriceHandler(ILogger<AddClientPriceHandler> logger,IMapper mapper,DatabaseContext db)
        {
            this.logger = logger;
            this.mapper = mapper;
            this.db = db;
        }
        public  async Task<ApiResult<int>> Handle(AddClientPriceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var clientPrice = mapper.Map<ClientPriceModel>(request);
            int r=await db.SqlSugar.Insertable(clientPrice).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "客户单价添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "客户单价添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
